<?php

require_once APPLICATION_PATH . '/../library/barcode/class/BCGFontFile.php';
require_once APPLICATION_PATH . '/../library/barcode/class/BCGColor.php';
require_once APPLICATION_PATH . '/../library/barcode/class/BCGDrawing.php';
require_once APPLICATION_PATH . '/../library/barcode/class/BCGcode39.barcode.php';

class LoginController extends GTL_Action {

    public function init() {
        parent::init();
    }

    public function indexAction() {

        $lgn_email = '';
        $data = array();
        $addData = '';
        $errorMessage = Array();
        $errorMessageArray = Array();
        $successmessage = '';
        $loginModel = new Model_Login();
        $loginForm = new Form_LoginForm();
        $this->view->mode = 'Add';


        if ($this->getRequest()->isPost()) {

            $postedData = $this->_request->getPost();
            if (!$loginForm->isValid($postedData)) {

                $errorMessage = $loginForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {

                if (count($errorMessageArray) > 0) {
                    
                } else {

                    $lgn_email = $postedData['lgn_email'];
                    $lgnData = $loginModel->checkEmailExist($lgn_email);
                    $lgn_id = $lgnData['lgn_id'];

                    if ($lgnData) {
                        $this->_helper->redirector('add', 'login', 'default', array('lgn_id' => $lgn_id));
                    } else {
                        if ($this->view->mode == 'Add') {
                            $addData['lgn_created'] = date('Y-m-d H:i:s');
                        }
                        $addData['lgn_id'] = $lgn_id;
                        $addData['lgn_email'] = $postedData['lgn_email'];
                        $addData['lgn_active'] = 2;
                        $addData['lgn_site_id'] = 1;

                        if (array_key_exists('lgn_signup', $_POST)) {
                            $addData['lgn_signup'] = $postedData['lgn_signup'];
                        }

                        $addData['lgn_modified'] = date('Y-m-d H:i:s');
                        $lgn_id = $loginModel->save($addData, 'lgn_id');

                        $this->_helper->redirector('add', 'login', 'default', array('lgn_id' => $lgn_id));
                    }
                }
            }
        }
        $this->view->errorMessage = $errorMessage;
        $this->view->form = $loginForm;
    }

    public function addAction() {

		$_SESSION['pagerefresh'] = 0;
        $lgn_id = '';
        $lgn_email = '';
        $lgn_active = '';
        $lgn_password = '';
        $confirm_password = '';
        $data = array();
        $addData = Array();
        $loginData = Array();
        $errorMessage = Array();
        $errorMessageArray = Array();
        $successmessage = '';
        $loginModel = new Model_Login();
        $addForm = new Form_AddForm();
        $stateArray = $this->getStateArray();
        $addForm->lgn_state->addMultiOptions($stateArray);
        $this->view->mode = 'Add';
        $this->view->showpassword = true;

        $diffArray = Array();
        $userData = Array();

        $displayArray = Array(
            //'lgn_email',
            //'lgn_fname',
            'lgn_lname',
            'lgn_state',
            'lgn_address',
            'lgn_city',
            'lgn_zipcode',
            'lgn_phone'
        );

        $couponArray = Array(
            'lgn_fname',
            'lgn_lname',
            'lgn_state',
            'lgn_address',
            'lgn_city',
            'lgn_zipcode',
            'lgn_phone'
        );

        //Check for the blog Parameter
        $addData['lgn_id'] = $this->_request->getParam('lgn_id');
        $lgn_id = (!empty($addData['lgn_id'])) ? $addData['lgn_id'] : null;

        if (!empty($lgn_id)) {
            //Set the Mode to Edit
            $this->view->mode = 'Edit';

            //email address readonly
            $addForm->lgn_email->setAttrib('readonly', 'readonly');

            //Fetch data to be loaded in form 
            $data = $loginModel->FetchEntryById($lgn_id);

            $userData = $data;
			
			
			//If all fields are prefilled than no need to come over this page	
			$_unfilledCount = 0;
			foreach($data as $_value) {
				if ( trim($_value) == '' ) {
					$_unfilledCount++;
				}
			}
			if ($_unfilledCount == 0) {
				//Redirect directly to the acknowledgement page
				$this->_helper->redirector('acknowledgement', 'login', 'default', array('lgn_id' => $lgn_id, 'loyality' => 'true'));
			}
			

            $lgn_active = $data['lgn_active'];

            if ($lgn_active == '2') {
                $this->view->showpassword = true;
            }

            if ($lgn_active == '1') {
                $this->view->showpassword = false;
            }
        }

        //Populate form 
        $this->view->form = $addForm->populate($data);

        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();

            $confirm_password = "";
            $lgn_password = "";

            if (array_key_exists('confirm_password', $postedData)) {
                $confirm_password = $postedData['confirm_password'];
            }

            if (array_key_exists('lgn_password', $postedData)) {
                $lgn_password = $postedData['lgn_password'];
            }

            //  validation for password and confirm password 
            if ($lgn_active == '2') {
                if ($lgn_password == "") {
                    $errorMessageArray[] = "Please enter password";
                }
                if ($confirm_password == "") {
                    $errorMessageArray[] = "Please enter confirm password";
                }
                if ($lgn_password != $confirm_password) {
                    $errorMessageArray[] = "Password and Confirm password are not match";
                }
            }



            if (!$addForm->isValid($postedData)) {

                $errorMessage = $addForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {


                if (count($errorMessageArray) > 0) {
                    
                } else {
					
                    if ($lgn_active == '1') {
                        $editcount = 0;
                        $postcount = 0;
                        $editArray = Array();
                        $postedDataArray = Array();

                        foreach ($displayArray as $_value) {

                            $editArray[$_value] = $data[$_value];
                            $postedDataArray[$_value] = $_POST[$_value];

                            if (array_key_exists($_value, $_POST)) {
                                if (trim($_POST[$_value]) != "") {
                                    $postcount++;
                                }
                            }

                            if (array_key_exists($_value, $data)) {
                                if (trim($data[$_value]) != "") {
                                    $editcount++;
                                }
                            }
                        }

                        //$couponArray

                        foreach ($postedDataArray as $key => $_value) {
                            if ($postedDataArray[$key] != $editArray[$key]) {
                                $diffArray[$key] = $_value;
                            }
                        }

                        $_SESSION['diff_array'] = $diffArray;

                        if ($postcount != count($displayArray)) {

                            if ($postcount < 1) {
                                $errorMessageArray[] = "Please enter at least one field";
                            } else {

                                if ($editcount == $postcount) {
                                    $errorMessageArray[] = "Please enter at least one field";
                                }
                            }
                        }
                    } else {
						//$_SESSION['diff_array'] = $_POST;
					}

                    if (count($errorMessageArray) > 0) {
                        
                    } else {

                        if ($this->view->mode == 'Add') {
                            $addData['lgn_created'] = date('Y-m-d H:i:s');
                        }

                        //Login user save
                        $addData = array();
                        $addData['lgn_id'] = $lgn_id;
                        $addData['lgn_email'] = $postedData['lgn_email'];

                        if ($lgn_active != '1') {
                            $addData['lgn_password'] = md5($postedData['lgn_password']);
                        }

                        //$addData['confirm_password'] = $postedData['confirm_password'];
                        $addData['lgn_fname'] = $postedData['lgn_fname'];
                        $addData['lgn_lname'] = $postedData['lgn_lname'];
                        $addData['lgn_zipcode'] = $postedData['lgn_zipcode'];
                        $addData['lgn_city'] = $postedData['lgn_city'];
                        $addData['lgn_state'] = $postedData['lgn_state'];
                        $addData['lgn_address'] = $postedData['lgn_address'];
                        //$addData['lgn_email'] = $postedData['lgn_email'];
                        $addData['lgn_phone'] = $postedData['lgn_phone'];
                        $addData['lgn_active'] = 1;

                        // update checkbox
                        if (!array_key_exists('lgn_signup', $_POST)) {
                            $addData['lgn_signup'] = 1;
                        }

                        $addData['lgn_modified'] = date('Y-m-d H:i:s');
                        $lgn_id = $loginModel->save($addData, 'lgn_id');

                        $state = "";
                        if (array_key_exists($postedData['lgn_state'], $stateArray)) {
                            if (trim($postedData['lgn_state']) != "") {
                                $state = $stateArray[$postedData['lgn_state']];
                            }
                        }

                        $couponLevel = 0;
                        //For the coupon code logic
                        if ($lgn_active == '1') {
						
							//echo "####"; 
							
							//print_r($couponArray);
							
							$diffCouponArray = Array();
							$editCouponArray = Array();
							$postedCouponDataArray = Array();
							
							foreach($couponArray as $_value) {
                              $editCouponArray[$_value] = $data[$_value];
                              $postedCouponDataArray[$_value] = $_POST[$_value];
							}

                              foreach($postedCouponDataArray as $key => $_value) {
								if ($postedCouponDataArray[$key] != $editCouponArray[$key]) {
									$diffCouponArray[$key] = $_value;
								}
                              }

                            
							$couponLevel = count($diffCouponArray);
							
							/*
                            //In Edit mode
                            foreach ($couponArray as $_value) {
                                if (array_key_exists($_value, $_POST)) {
                                    if (trim($_POST[$_value]) != "") {
                                        $couponLevel++;
                                    }
                                }
                            }
							*/

                            /*
                              

                              
                             */
                        } else {

                            //In Add mode 
                            foreach ($couponArray as $_value) {
                                if (array_key_exists($_value, $_POST)) {
                                    if (trim($_POST[$_value]) != "") {
                                        $couponLevel++;
                                    }
                                }
                            }
                        }

                        if ($couponLevel > 0) {
                            $couponInsertArray = Array();
                            //$couponInsertArray['dis_lgn_id'] = $lgn_id;
                            $couponInsertArray['dis_level'] = $couponLevel;

                            $modelDiscount = new Model_Discount ();
                            $latestDiscount = $modelDiscount->fetchnextNum($couponLevel);

                            if ($latestDiscount) {
                                $couponInsertArray['dis_nextnum'] = $latestDiscount + 1;
								
                                $dis_couponcode = 'C' . $couponInsertArray['dis_nextnum'];
                            } else {
                                $couponInsertArray['dis_nextnum'] = $couponLevel * 1000000;
                                $dis_couponcode = 'C' . $couponInsertArray['dis_nextnum'];
                            }

                            $couponInsertArray['dis_endnum'] = ($couponLevel * 1000000) + 999999;
                            $couponInsertArray['dis_text'] = $this->getDiscountText($couponLevel);
                            $couponInsertArray['dis_createdate'] = date('Y-m-d H:i:s');
                            $couponInsertArray['dis_expirationdate'] = date('Y-m-d H:i:s', strtotime("+30 day"));
                            $couponInsertArray['dis_status'] = 1;

                            $dis_id = $modelDiscount->save($couponInsertArray, 'dis_id');


                            $font = new BCGFontFile(APPLICATION_PATH . '/../library/barcode/font/Arial.ttf', 18);
                            // Don't forget to sanitize user inputs
                            $text = $dis_couponcode;

                            // The arguments are R, G, B for color.
                            $color_black = new BCGColor(0, 0, 0);
                            $color_white = new BCGColor(255, 255, 255);

                            $drawException = null;
                            try {
                                $code = new BCGcode39();
                                $code->setScale(3); // Resolution
                                $code->setThickness(30); // Thickness
                                $code->setForegroundColor($color_black); // Color of bars
                                $code->setBackgroundColor($color_white); // Color of spaces
                                $code->setFont($font); // Font (or 0)
                                $code->parse($text); // Text
                            } catch (Exception $exception) {
                                $drawException = $exception;
                            }
                            $drawing = new BCGDrawing('', $color_white);
                            if ($drawException) {
                                $drawing->drawException($drawException);
                            } else {
                                $drawing->setBarcode($code);
                                $drawing->draw();
                                $folder = $this->config->UPLOAD_PATH . "loyality/";
                                $filename = $text . ".jpeg";
                                $drawing->setFilename($folder . $filename);
                                $drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
                            }
                        }


                        $html = new Zend_View();
                        $html->setScriptPath(APPLICATION_PATH . '/modules/default/views/scripts/mailtemplate/');

                        $html->assign('BASE_URL', $this->config->BASE_URL);
                        $html->assign('COUPON_CODE', $filename);
                        $html->assign('COUPON', $couponInsertArray['dis_nextnum']);
                        $html->assign('FIRSTNAME', $postedData['lgn_fname']);
                        $html->assign('LASTNAME', $postedData['lgn_lname']);
                        $html->assign('EXP_DATE', $couponInsertArray['dis_expirationdate']);
                        $html->assign('DATE', $couponInsertArray['dis_createdate']);
                        $body = $html->render('mail.phtml');
						
                        $metaDataModel = new Model_Metadata();
                        $ADMIN_MAIL_DATA = $metaDataModel->fetchEntryByKey("ADMIN_FROM_EMAIL");
                        $ADMIN_MAIL = $ADMIN_MAIL_DATA['mtd_value'];

                        $ADMIN_FROM_DATA = $metaDataModel->fetchEntryByKey("ADMIN_FROM_NAME");
                        $ADMIN_FROM = $ADMIN_FROM_DATA['mtd_value'];

                        $mail = new Zend_Mail();
                        $mail->setBodyText($body);
						//echo $body; exit;
                        $mail->setBodyHtml($body, "iso-8859-1");
                        $mail->addTo($postedData['lgn_email'], $postedData['lgn_fname']);
                        $mail->setFrom($ADMIN_MAIL, $ADMIN_FROM);
                        $mail->setReplyTo($ADMIN_MAIL, $ADMIN_FROM);
                        $mailSubject = "Thank you For Signup";
                        $mail->addHeader('MIME-Version', '1.0');
                        $mail->addHeader('Content-Transfer-Encoding', '8bit');
                        $mail->addHeader('X-Mailer:', 'PHP/' . phpversion());
                        $mail->setSubject($mailSubject);

                        try {
                            //$mail->send();
                            $addForm->reset();
                            if ($this->view->mode == 'Add') {
                                $successmessage = 'Login Data add successfully';
                            } else {
                                $successmessage = 'Login Data updated successfully';
                            }
                            $this->addSuccessMessage($successmessage);
                            $this->_helper->redirector('acknowledgement', 'login', 'default', array('lgn_id' => $lgn_id));
                        } catch (Zend_Exception $e) {
                            $errorMessageArray[] = 'Some error occur while sending mail.';
                        }
                    }
                }
            }
        }

        $this->view->userData = $userData;
        $this->view->lgn_id = $lgn_id;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $addForm;
    }

    public function getDiscountText($couponlevel) {
        switch ($couponlevel) {
            case 1:
                $discountlevel = 5;
                break;

            case 2:
                $discountlevel = 6;
                break;

            case 3:
                $discountlevel = 7;
                break;

            case 4:
                $discountlevel = 8;
                break;

            case 5:
                $discountlevel = 9;
                break;

            case 6:
                $discountlevel = 10;
                break;

            case 7:
                $discountlevel = 15;
                break;
        }

        return $discountlevel . "% Discount";
    }

    public function getStateArray() {
        $stateArray = Array(
            "" => "-- Select state --",
            "AL" => "Alabama",
            "AK" => "Alaska",
            "AZ" => "Arizona",
            "AR" => "Arkansas",
            "CA" => "California",
            "CO" => "Colorado",
            "CT" => "Connecticut",
            "DE" => "Delaware",
            "DC" => "District Of Columbia",
            "FL" => "Florida",
            "GA" => "Georgia",
            "HI" => "Hawaii",
            "ID" => "Idaho",
            "IL" => "Illinois",
            "IN" => "Indiana",
            "IA" => "Iowa",
            "KS" => "Kansas",
            "KY" => "Kentucky",
            "LA" => "Louisiana",
            "ME" => "Maine",
            "MD" => "Maryland",
            "MA" => "Massachusetts",
            "MI" => "Michigan",
            "MN" => "Minnesota",
            "MS" => "Mississippi",
            "MO" => "Missouri",
            "MT" => "Montana",
            "NE" => "Nebraska",
            "NV" => "Nevada",
            "NH" => "New Hampshire",
            "NJ" => "New Jersey",
            "NM" => "New Mexico",
            "NY" => "New York",
            "NC" => "North Carolina",
            "ND" => "North Dakota",
            "OH" => "Ohio",
            "OK" => "Oklahoma",
            "OR" => "Oregon",
            "PA" => "Pennsylvania",
            "RI" => "Rhode Island",
            "SC" => "South Carolina",
            "SD" => "South Dakota",
            "TN" => "Tennessee",
            "TX" => "Texas",
            "UT" => "Utah",
            "VT" => "Vermont",
            "VA" => "Virginia",
            "WA" => "Washington",
            "WV" => "West Virginia",
            "WI" => "Wisconsin",
            "WY" => "Wyoming"
        );
        return $stateArray;
    }

    public function acknowledgementAction() {
        $lgn_id = '';
        $value = '';
        $lgn_fname = '';
		
		$pageRefresh = 0;
		if (!array_key_exists('pagerefresh', $_SESSION)) {
			$_SESSION['pagerefresh'] = $pageRefresh;
		}
		
		
        $data = array();
        $addData = Array();
        $loginModel = new Model_Login();
        $addForm = new Form_AddForm();
        $stateArray = $this->getStateArray();
        $this->view->stateArray = $stateArray;
		
		
		//Check for the redirector Parameter
		$loyality = $this->_request->getParam('loyality');
        $loyality = (!empty($loyality)) ? $loyality : false;
		$this->view->loyality = $loyality;	
		
		
        //Check for the blog Parameter
        $addData['lgn_id'] = $this->_request->getParam('lgn_id');
        $lgn_id = (!empty($addData['lgn_id'])) ? $addData['lgn_id'] : null;

        if (!empty($lgn_id)) {
            //Fetch data to be loaded in form 
            $data = $loginModel->FetchEntryById($lgn_id);
        }

        $this->view->data = $data;
        $this->view->lgn_id = $lgn_id;
        $this->view->form = $addForm;
    }

}

?>